﻿using IOA.MES.Business;
using IOA.MES.DataAccess.VModel;
using IOA.MES.Log.DataAccess.Enum;
using IOA.MES.Log.DataAccess.VModel;
using IOA.MES.Web.App_Start;
using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Web.Mvc;

namespace IOA.MES.Web.Controllers
{
    public class AuthController : Controller
    {
        /// <summary>
        /// 登录页
        /// </summary>
        public ActionResult Login(string ReturnUrl = "")
        {
            var files = System.IO.Directory.GetFiles(Server.MapPath("/res/lang"));
            var langs = files.Select(_ => _.Substring(_.LastIndexOf("\\") + 1, _.Length - _.LastIndexOf("\\") - 6)).OrderByDescending(_ => _).ToList();
            new FormsAuthenticationService().SignOut();
            ViewBag.ReturnUrl = string.IsNullOrWhiteSpace(ReturnUrl) ? "/" : ReturnUrl;
            return View(langs);
        }

        /// <summary>
        /// 登录接口
        /// </summary>
        [HttpPost]
        public JsonResult Login(string userName, string password, string lang)
        {
            var user = new UserMgr().Login(userName, password, lang, new VLoginHistory
            {
                ClientType = ClientType.MESWeb,
                DeviceType = BaseEnv.DeviceType,
                ClientIP = BaseEnv.ClientIP,
                UserAgent = System.Web.HttpContext.Current.Request.UserAgent.ToLower()
            });
            new FormsAuthenticationService().SignIn(user.PkId.ToString(), false);
            new UserMgr().AddToken(new VUserToken
            {
                UserId = user.PkId,
                CreateBy = user.PkId,
                Expires = DateTime.Now.AddYears(1),
                Token = Response.Cookies[".MES"].Value
            });
            Response.Cookies.Add(new System.Web.HttpCookie("Token", Response.Cookies[".MES"].Value));
            return Json(new ResultJson<dynamic>());
        }

        /// <summary>
        /// 退出登录
        /// </summary>
        [HttpPost]
        public JsonResult Logout()
        {
            new UserMgr().Logout(Request.Cookies[".MES"].Value);
            return Json(new ResultJson<dynamic>());
        }

        /// <summary>
        /// 获取语言包接口
        /// </summary>
        [HttpPost]
        public JsonResult GetLang(string lang)
        {
            var langFile = $"{Server.MapPath("/res/lang/")}{lang}.json";

            string json = string.Empty;
            using (var fs = new FileStream(langFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                using (StreamReader sr = new StreamReader(fs, Encoding.UTF8))
                {
                    json = sr.ReadToEnd().ToString();
                }
            }
            return Json(new ResultJson<string>(json));
        }
    }
}
